<?php
namespace Controller;
use Slim\Container;
class Base{
    protected $db;
    protected $view;
    protected $logger;
    protected $assign;
    protected $checkfrom;
    protected $guard;
    protected $account;
    protected $page;
    protected $redis;
    protected $weichat;
    protected $curl;
    protected $msg;
    public function __construct(Container $container)
    {

        $this->db=$container->get('db');
        $this->view=$container->get('view');
        $this->logger=$container->get('logger');
        $this->checkfrom=$container->get('checkfrom');
        $this->guard=$container->get('guard');
        $this->page=$container->get('page');
        $this->type=$container->get('type');
        $this->redis=$container->get('redis');
        $this->weichat=$container->get('weichat');
        $this->curl=$container->get('curl');
        $this->msg=$container->get('msg');
    }
    public function getaccount(){
        if(isset($_SESSION['account_id'])===true){
            $account=$this->db->where(['id'=>(int)$_SESSION['account_id']])->find('tcp_account');
            if(!empty($account)){
                return $account;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    public function checkuploadfile()
    {
        $filepath = SYSTEM_PATH . '/public/upload';
        $thumbfilepath = $filepath . '/thumb';

        if (file_exists($filepath) === false) {
            @mkdir($filepath);
        }
        if (file_exists($thumbfilepath) === false) {
            @mkdir($thumbfilepath);

        }


        return [
            'filepath' => $filepath,
            'thumbfilepath' => $thumbfilepath,

        ];
    }
    public  function checksize($size,$maxsize)
    {
        $kb = 1024;   // Kilobyte
        $mb = 1024 * $kb; // Megabyte
        $gb = 1024 * $mb; // Gigabyte
        if ($size < $kb) {
            return true;
        } elseif ($size < $mb) {
            return true;

        } elseif ($size < $gb) {
            if(round($size / $mb)<=$maxsize){
                return true;
            }else{
                return false;
            }
        } else {
            return false;
        }
    }
    public  function  getarray($array){
        echo "<pre>";
        print_r($array);
        exit;
    }
    public function encode_base64($sData)
    {
        $sBase64 = base64_encode($sData);
        return strtr($sBase64, '+/', '-_');
    }

    public function decode_base64($sData)
    {
        $sBase64 = strtr($sData, '-_', '+/');
        return base64_decode($sBase64);
    }

    function unescape($str){
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++){
            if ($str[$i] == '%' && $str[$i+1] == 'u'){
                $val = hexdec(substr($str, $i+2, 4));
                if ($val < 0x7f) $ret .= chr($val);
                else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
                else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
                $i += 5;
            }elseif ($str[$i] == '%'){
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            }else{
                $ret .= $str[$i];
            }
        }
        return $ret;
    }
    public function __destruct(){
        unset($this->db);
        unset($this->view);
        unset($this->logger);
        unset($this->checkfrom);
        unset($this->guard);
        unset($this->type);
        unset($this->assign);
        unset($this->account);

    }
    function remove_xss($val) {
        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        //$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
        $val = preg_replace('/([\x00-\x08\x0b-\x0c\x0e-\x19])/', '', $val);
        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=@avascript:alert('XSS')>
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            // ;? matches the ;, which is optional
            // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
            // @ @ search for the hex values
            $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
            // @ @ 0{0,7} matches '0' zero to seven times
            $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
        }
        // now the only remaining whitespace attacks are \t, \n, and \r
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);
        $found = true; // keep replacing as long as the previous round replaced something
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(�{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    // no replacements were made, so exit the loop
                    $found = false;
                }
            }
        }
        return $val;
    }
    //0审核中1上传失败2审核未通过3审核通过
    public  function  getStateTxt($state){
        switch ($state){
            case 0:return '审核中';break;
            case 1:return '上传失败';break;
            case 2:return '审核未通过';break;
            case 3:return '审核通过';break;
            default:return '审核中';break;

        }
    }
    public function getUser(){
        if(isset($_SESSION['uid'])&&!empty($_SESSION['uid'])){
            $where['uid']=array($_SESSION['uid']);
            $user = $this->db->where($where)->find('tcp_user');
            $user['headimg']=isset($_SESSION['headimg'])?$_SESSION['headimg']:'';
            return $user;
        }else{
            return 0;
        }
    }
    public function checkweichat($user){
        $weichat=$this->weichat;
        $tcp_token=$this->redis->get('tcp_token');
        if(!empty($tcp_token)&&!empty($user)){
            require_once SYSTEM_PATH . "/app/lib/jssdk.php";
            $jssdk = new \JSSDK($weichat['appid'], $weichat['appsecret']);
            $signPackage = $jssdk->GetSignPackage();
            $this->assign = [
                'openid'=>$user['openid'],
                'signPackage'=>$signPackage,
            ];

        }else{
            // 第一步：用户同意授权，获取code
            $callbackurl=$_SERVER['REQUEST_URI'];

            //snsapi_userinfo  snsapi_base
            $codeurl=sprintf('https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect',$weichat['appid'],$weichat['redirect_uri'],$callbackurl);
            header('Location:'.$codeurl);
            exit;
        }
    }
    public  function setToken(){
        $this->guard->generateToken();
        $this->assign['tk_name'] = $this->guard->getTokenName();
        $this->assign['tk_value'] = $this->guard->getTokenValue();
    }
    public  function getDate(){

        $t=time();
        $date=[];
        for($i=1;$i<7;$i++){
            $t-=$i*24*3600;
            $date[]=strtotime(date('Y-m-d',$t));

        }
        return $date;
    }


}